import json
import re

from django.contrib.auth import logout
from django.core.cache import cache
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.areas.models import Area, Address


# 获取省
from utils.views import LoginRequiredJSONMixin


class AreasView(View):

    def get(self, request):

        # django提供了cache模块去做缓存
        province_list = cache.get('provinces')
        # print('缓存的数据：',province_list)

        if not province_list:
            # print('没有缓存，去存缓存')
            # 1. 去数据库查询所有的省份数据
            try:
                areas = Area.objects.filter(parent=None)
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': '获取省份失败，网络异常'})

            province_list = []

            for a in areas:
                province_list.append({'id': a.id, 'name': a.name})

            # 存到缓存
            cache.set('provinces', province_list, 3600 * 24 * 30)
        else:

            pass
            # print('有缓存，直接返回')
        # 有的话直接返回数据

        return JsonResponse({'code': 200, 'province_list': province_list})


# 获取市区
class SubAreasView(View):

    def get(self, request, area_id):

        # 去缓存找
        subs = cache.get('cities_{}'.format(area_id))

        if not subs:

            # 提供市或区数据
            try:
                subareas = Area.objects.filter(parent_id=area_id)
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': '获取市区失败，网络异常'})

            # 3. 把下一级数据  做拼接
            subs = []

            for a in subareas:
                subs.append({'id': a.id, 'name': a.name})

            # 把数据存到缓存
            cache.set('cities_{}'.format(area_id), subs, 3600 * 24 * 30)

        else:
            pass
            # print('走的缓存')

        return JsonResponse({'code': 0, 'sub_data': {'subs': subs}})


class AddressView(LoginRequiredJSONMixin,View):

    #  保存收货地址
    def post(self, request):

        # 1. 获取数据
        body = request.body
        data_dict = json.loads(body)
        receiver = data_dict.get('receiver')
        province_id = data_dict.get('province_id')
        city_id = data_dict.get('city_id')
        district_id = data_dict.get('district_id')
        place = data_dict.get('place')
        mobile = data_dict.get('mobile')
        tel = data_dict.get('tel')
        email = data_dict.get('email')

        # 2.校验
        if not all([receiver, province_id, city_id, district_id, place, mobile, tel, email]):
            return JsonResponse({'code': 404, 'message': '填写的数据不全'})

        # 3. 使用address模型类添加数据

        try:
            address = Address.objects.create(user=request.user,
                                             title=receiver,
                                             receiver=receiver,
                                             province_id=province_id,
                                             city_id=city_id,
                                             district_id=district_id,
                                             place=place,
                                             mobile=mobile,
                                             tel=tel,
                                             email=email)

            request.user.default_address = address.id
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 404, 'message': '保存失败'})

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        return JsonResponse({'code': 0, 'message': 'OK', 'address': address_dict,
                             })

    #  收货人信息
    def get(self, request):
        # 1. 获取用户对象
        user = request.user
        print(user)
        try:
            addresses = user.addresses.all().filter(is_deleted=False)
            # 创建一个空列表，存地址的字典数据
            address_dict_list = []

            for address in addresses:
                address_dict = {
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email
                }
                # - 3拼接列表
                address_dict_list.insert(0, address_dict)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 501, 'errmsg': '查询失败'})

        return JsonResponse({'code': 0, 'message': 'OK', 'addresses': address_dict_list,
                             'default_address_id': request.user.default_address})

    # 修改收货地址
    def put(self,request,address_id):

        data = json.loads(request.body.decode())
        # {'id': 13, 'title': '马金涛', 'receiver': '马金涛', 'province': '北京市', 'city': '北京市', 'district': '东城区',
        #  'place': '东城小区', 'mobile': '19831803530', 'tel': '010-123456', 'email': '116@qq.com', 'province_id': 360000,
        #  'city_id': 360700, 'district_id': 360727}
        receiver = data.get('receiver')
        province_id = data.get('province_id')
        city_id = data.get('city_id')
        district_id = data.get('district_id')
        place = data.get('place')
        mobile = data.get('mobile')
        tel = data.get('tel')
        email = data.get('email')

        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code':300,'message':'数据填写不全'})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400,
                                      'errmsg': '参数mobile有误'})

        # if tel:
        #     if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
        #         return JsonResponse({'code': 400,'errmsg': '参数tel有误'})

        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 400,'errmsg': '参数email有误'})

        # 判断地址是否存在，并更新地址信息
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'message':'更新地址失败，检查数据库！'})


        # 构造相应数据
        address = Address.objects.get(id=address_id)

        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }


        return JsonResponse({'code':0,'message':'OK','address':address_dict})

    # 删除收货地址
    def delete(self, request,address_id):

        try:
            address = Address.objects.get(id=address_id)
            print(address_id)


            address.is_deleted = True
            address.save()


        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'message':'删除地址失败'})
        return JsonResponse({'code': 0, 'message': '删除地址成功'})


# 设置默认地址
class DefaultAddressView(View):

    # 设置默认地址
    def put(self, request, address_id):

        user = request.user
        # 查询数据库
        try:
            user.default_address = address_id
            user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 300, 'message': '查询失败'})

        return JsonResponse({'code': 0, 'message': '设置默认地址成功！'})


# 修改地址标题
class UpdateTitleAddressView(View):


    def put(self,request,address_id):
        # print(address_id)

        # 1.接收参数，地址标题
        json_data = json.loads(request.body.decode())
        data = json_data.get('title')


        # 2. 查询地址
        try:
            address = Address.objects.get(id=address_id)

            address.title = data
            address.save()

        except Exception as e:
            print(e)
            return JsonResponse({'code':402,'message':'查询失败'})



        return JsonResponse({'code':200,'message':'OK'})



# 修改密码
class ChangePasswordView(View):
    def put(self,request):
        # 1. 接收参数
        data = json.loads(request.body.decode())

        old_password = data.get('old_password')
        new_password = data.get('new_password')
        new_password2 = data.get('new_password2')


        # 2. 校验参数
        if not all([old_password,new_password,new_password2]):

            return JsonResponse({'code':400,'message':'缺少参数'})

        result = request.user.check_password(old_password)


        if not result:
            return JsonResponse({'code':400,'message':'原始密码不正确'})

        if not re.match(r'^[0-9A-Za-z]{8,20}$', new_password):
            return JsonResponse({'code': 400,
                                      'errmsg': '密码最少8位,最长20位'})

        if new_password != new_password2:
            return JsonResponse({'code': 400,
                                      'errmsg': '两次输入密码不一致'})



        # 3. 修改密码
        try:
            request.user.set_password(new_password)
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'message':'修改密码失败'})


        # 清理状态保持信息
        logout(request)


        response = JsonResponse({'code':0,'message':'OK'})

        response.delete_cookie('username')



        return response
    
    
    